/**
 * 报表元数据table
 * @param trData trData
 * @constructor
 */
var ReportMateTable = function (trData) {

    var self = this;
    this.trData = trData || [];
    this.metaDataTemplate = _.template('\
        <tr style="display: none;">\
            <td><input class="form-control" name="name" value="{{name}}"/></td>\
            <td><input class="form-control" name="title" value="{{title}}"/></td>\
            <td><input class="form-control" name="type" value="{{type}}"/></td>\
            <td>\
                <select name="columnType" class="form-control">\
                    <option {{dataTypeSelected1}} value="1">布局</option>\
                    <option {{dataTypeSelected2}} value="2">维度</option>\
                    <option {{dataTypeSelected3}} value="3">统计</option>\
                    <option {{dataTypeSelected4}} value="4">计算</option>\
                </select>\
            </td>\
            <td><input name="width" id="width" class="form-control" value="{{width}}"/></td>\
            <td><input name="precision" class="form-control" value="{{precision}}"/></td>\
            <td>\
                <select name="sort" class="form-control">\
                    <option>默认</option>\
                    <option>排序A</option>\
                    <option>排序B</option>\
                </select >\
            </td>\
            <td class="hidden-480">\
                <label class="checkbox-inline">\
                    <input type="checkbox" name="optional" class="ace">\
                    <span class="lbl"> 可选</span>\
                </label>\
                <label class="checkbox-inline">\
                    <input type="checkbox" name="rate" class="ace">\
                    <span class="lbl"> 百分比</span>\
                </label>\
            </td>\
        </tr>\
    ');
    var elementAry = _.map(trData, function (o) {
        return self.metaDataTemplate(o);
    });
    // table id
    this.tableId = 'report_mate_table';
    // 私有
    this._tableId = '#report_mate_table';
    // 表格模版
    this.view = _.template('\
     <div id="report_mate_widget" class="widget-box ui-sortable-handle">\
        <div class="widget-header">\
            <h5 class="widget-title lighter smaller">元数据列配置</h5>\
            <div class="widget-toolbar">\
                <div class="widget-menu">\
                <a href="#" id="report_mate_widget_up"><i class="ace-icon fa fa-chevron-up"></i></a>\
                <a href="#" id="report_mate_widget_down"><i class="ace-icon fa fa-chevron-down"></i></a>\
                <a href="#" id="report_mate_widget_add"><i class="ace-icon fa fa-plus green"></i></a>\
                <a href="#" id="report_mate_widget_minus"><i class="ace-icon fa fa-minus red"></i></a>\
                <a href="#" data-action="fullscreen" class="orange2"><i class="ace-icon fa fa-expand"></i></a>\
                </div>\
            </div>\
        </div>\
        <div class="widget-body">\
            <div class="widget-main no-padding">\
                <table id="report_mate_table" class="table table-bordered">\
                    <thead class="thin-border-bottom">\
                        <tr>\
                            <th>列名</th><th>标题</th><th>类型</th><th>数据类型</th>\
                            <th>宽度</th><th>精度</th><th>排序类型</th><th class="hidden-480">配置</th>\
                        </tr>\
                    </thead>\
                    <tbody>{{tbody}}</tbody>\
                </table>\
            </div>\
        </div>\
     </div>\
    ')({tbody: elementAry.join('')});

};
ReportMateTable.prototype = {
    init: function () {
        this.trData = [];
        this.byDelegateEvent();
    },
    /**
     * 添加一行
     * @param data
     */
    addRow: function (data) {
        this.trData.push(data);
        var columnType = data.columnType === undefined ? 0 : data.columnType;
        data = $.extend({}, data, {
            dataTypeSelected1: columnType === 1 || columnType === '1' ? 'selected' : '',
            dataTypeSelected2: columnType === 2 || columnType === '2' ? 'selected' : '',
            dataTypeSelected3: columnType === 3 || columnType === '3' ? 'selected' : '',
            dataTypeSelected4: columnType === 4 || columnType === '4' ? 'selected' : ''
        });
        $(this._tableId).children('tbody').append(this.metaDataTemplate(data)).children('tr:last').fadeIn();
    },
    /**
     * 添加多行
     * @param data
     */
    addRows: function (datas) {
        datas = datas || [];
        var self = this;
        datas.forEach(function (data) {
            self.addRow(data);
        });

    },
    /**
     * 删除一行
     * @param rowNumber 行数
     */
    removeRow: function (rowNumber) {
        this.trData.splice(rowNumber, 1);
        $(this._tableId).children('tbody').children('tr:eq(' + rowNumber + ')')
            .fadeOut('fast', function () {
                $(this).remove();
            });
    },
    /**
     * 添加点击选择功能
     */
    byDelegateEvent: function () {
        var self = this;
        // 绑定table tr点击事件
        var $table = $(this._tableId);
        $table.delegate('tbody>tr', 'click', function (event) {
            // 选择后的高亮颜色
            var $currentTarget = $(event.currentTarget);
            // 取消所有兄弟元素的选择标识，取消所有兄弟元素的高亮
            $currentTarget.siblings().removeData('selected', undefined).removeClass('success');
            !$currentTarget.hasClass('success') && $currentTarget.addClass('success');
        });
        $table.delegate('tbody>tr>td>input,tbody>tr>td>textarea,tbody>tr>td>select,tbody>tr>td>label>input', 'change', function (event) {
            var $target = $(event.currentTarget);
            var index = $target.closest('tr').index();
            var name = $target.prop('name');
            self.trData[index][name] = $target.val();
            event.preventDefault();
        });
        // 绑定widget事件
        $('#report_mate_widget_add').on('click', function (e) {
            self.addRow({
                name: '',
                title: '',
                type: '',
                columnType: 1,
                width: '30',
                precision: 0,
                sortType: '默认',
                configuration: '配置'
            });
            e.preventDefault();
        });
        $('#report_mate_widget_minus').on('click', function (e) {
            $table.children('tbody').children('tr').each(function (index, item) {
                $(item).hasClass('success') && self.removeRow($(item).index());
            });
            e.preventDefault();
        });
        $('#report_mate_widget_down').on('click', function (e) {
            $table.children('tbody').children('tr').each(function (index, item) {
                var $tr = $(item);
                if ($tr.hasClass('success')) {
                    if (null !== $tr.next().html()) {
                        var idx = $tr.index();
                        $.xumf.array.moveDown(self.trData, idx);
                        $tr.insertAfter($tr.next());
                    }
                }
            });
            e.preventDefault();
        });
        $('#report_mate_widget_up').on('click', function (e) {
            $table.children('tbody').children('tr').each(function (index, item) {
                var $tr = $(item);
                if ($tr.hasClass('success')) {
                    if (null !== $tr.prev().html()) {
                        var idx = $tr.index();
                        $.xumf.array.moveUp(self.trData, idx);
                        $tr.insertBefore($tr.prev());
                    }
                }
            });
            e.preventDefault();
        });
    }
};
